package com.example.f8399.testdemo.activity;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.example.f8399.testdemo.BaseActivity;
import com.example.f8399.testdemo.R;
import com.example.f8399.testdemo.databinding.ActivityDownloadBinding;

import java.io.File;
import java.net.URI;
import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author lcfeng
 * @description 文件下载管理，
 * 参考：https://www.101apps.co.za/articles/using-the-downloadmanager-to-manage-your-downloads.html.
 * @date 2018/7/18 11:26.
 **/
public class DownloadActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks{

    ActivityDownloadBinding mBinding;
    private DownloadManager mDownloadManager;
    private String mImgUrl;
    private long mDownloadReference;
    private BroadcastReceiver receiverDownloadComplete;
    private BroadcastReceiver receiverNotificationClicked;

    private String[] premissList = new String[]{Manifest.permission.INTERNET,Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_download);
        mBinding.setAc(this);

        initView();
    }



    public void downloadImage(View view) {

        if (EasyPermissions.hasPermissions(this, premissList)) {
            downloadApk();
        }else {
            EasyPermissions.requestPermissions(this,"只有授权之后才可以更新版本",1000,premissList);
        }

    }

    private void downloadApk() {

        Uri uri = Uri.parse(mImgUrl);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDescription("图片哦");
        request.setTitle("通知我勒个去啊");
        //是否在系统app下载界面可见，默认是true ，所有这个有没有都可以
        request.setVisibleInDownloadsUi(true);
        //文件只能下载到外部存储控件，这个指定的是和app所属同一位置的文件夹
        request.setDestinationInExternalFilesDir(DownloadActivity.this, Environment.DIRECTORY_DOWNLOADS, "time.apk");
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        mDownloadReference = mDownloadManager.enqueue(request);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //筛选器的作用是因为隐式跳转有好多界面，你需要挑出来你需要的进行
        IntentFilter intentFilter_notify = new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        IntentFilter intentFilter_complete = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

        receiverNotificationClicked = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String ids = DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS;
                long[] longArrayExtra = intent.getLongArrayExtra(ids);
                for (long l : longArrayExtra) {
                    if (l == mDownloadReference) {
                        ToastUtils.showShort("hi，我抓到了");
                    }
                }
            }
        };

        receiverDownloadComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long extra = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (extra == mDownloadReference) {
                    ToastUtils.showShort("下载完毕了哦");

                    Uri uriForDownloadedFile = mDownloadManager.getUriForDownloadedFile(mDownloadReference);

                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(mDownloadReference);
                    Cursor query1 = mDownloadManager.query(query);
                    if (query1 != null&&query1.moveToFirst()) {

                        String path = query1.getString(query1.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                        installApp(path);
                    }
                }
            }
        };

        registerReceiver(receiverNotificationClicked, intentFilter_notify);
        registerReceiver(receiverDownloadComplete, intentFilter_complete);
    }

    private void installApp(String filepath) {

        File file1 = new File(filepath.substring(7));

        Intent install = new Intent(Intent.ACTION_VIEW);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            Uri uriForFile = FileProvider.getUriForFile(this, "com.example.f8399.testdemo.provider", file1);
            install.setDataAndType(uriForFile, "application/vnd.android.package-archive");
        }else {
            install.setDataAndType(Uri.fromFile(file1), "application/vnd.android.package-archive");
        }
        this.getApplicationContext().startActivity(install);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiverNotificationClicked);
        unregisterReceiver(receiverDownloadComplete);
    }

    private void initView() {
        mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//        mImgUrl = "http://img95.699pic.com/desgin_photo/40023/5819_list.jpg";
        mImgUrl = "https://d-03.winudf.com/b/apk/Y29tLnR5d2hvbGxhbmQuc2ltcGxldGltZXJfMTZfOTE1YmVlNzM?_fn=U2ltcGxlIFRpbWVyX3YxLjZfYXBrcHVyZS5jb20uYXBr&_p=Y29tLnR5d2hvbGxhbmQuc2ltcGxldGltZXI&as=fc21d02cbbc74ad32bf40dffbea444885b52dac6&c=1%7CTOOLS%7CZGV2PVR5d2hvbGxhbmQmdm49MS42JnZjPTE2&k=06c936345724480a05a5f1c10dbdb0f25b561ade";
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, Arrays.asList(premissList))) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
}
